#coding:utf-8

import wx
import wx.gizmos as gz
import wx.aui as aui
import wx.lib.mixins.listctrl as listmix
import wx.lib.scrolledpanel as scrolled
import customwid as wid
import ico
from report import RecordInfo, RecordConnection
from database import Dbapi
import buss.market as market
import datamethod as dm



record_info = None


class RecordPanel(scrolled.ScrolledPanel):
    def __init__(self, parent, mark):
        scrolled.ScrolledPanel.__init__(self, parent)
        self.SetBackgroundColour(wx.WHITE)
        
        busstype, bussdata = record_info.getTestCaseData(mark)
        testname = market.findProtocol(dm.str2data(busstype)).getName()
        repeat, patience, rest = record_info.getTestCaseOption(mark)
        
        items = (
                (u"业务名称:", testname),
                (u"业务类型:", busstype),
                (u"业务数据:", bussdata),
                (u"重复次数:", str(repeat)),
                (u"忍耐时间:", str(patience)),
                (u"停留时间:", str(rest)),
                )
        
        datas = record_info.getRecordData(mark)
        cls = market.findInterpreter(busstype)
        panel = cls(datas).interprete(self)
        
        self.mainsizer = wid.Sizer(wx.VERTICAL, flag = wx.ALL|wx.EXPAND, border = 5)
        
        for title, caption in items:
            item = wid.TitleTextLabel(self, title, caption)
            self.mainsizer.Add(item)
        
        self.mainsizer.Add(panel, proportion=1, border = 10)
        self.SetSizer(self.mainsizer)
        self.Fit()
        self.SetupScrolling()

    def showPanel(self):
        pass
        
class RecordList(gz.TreeListCtrl, listmix.ListCtrlAutoWidthMixin):
    
    def __init__(self, parent):
        gz.TreeListCtrl.__init__(self, parent, style = wx.TR_DEFAULT_STYLE|
                                    wx.TR_FULL_ROW_HIGHLIGHT|wx.TR_HIDE_ROOT)
        listmix.ListCtrlAutoWidthMixin.__init__(self)
        columns = ((u"测试用例", 175),
                   (u"开始时间", 175),
                   (u"结束时间", 175),
                   (u"连发次数", 175),
                   (u"忍耐时间", 175),
                   (u"停留时间", 175),
                   )
        for name, width in columns:
            self.AddColumn(name, width = width)
        self.root = self.AddRoot('root')
        self.Bind(wx.EVT_TREE_ITEM_ACTIVATED, self.OnShowRecord)
        
    def insertRecord(self, id, begin, end, busstype, bussdata, 
                     repeat, patience, rest):
        buss = market.findProtocol(busstype)
        testname = u""
        if buss:
            testname = buss.getName()
        item = self.AppendItem(self.root, testname)
        x = [begin, end, repeat, patience, rest]
        for i in range(len(x)):
            self.SetItemText(item, str(x[i]), i+1)
        self.SetPyData(item, id)
        return item
    
    def OnShowRecord(self, evt):
        mark = self.GetPyData(evt.GetItem())
        self.GetParent().showRecord(mark)
           

class GeneralWindow(scrolled.ScrolledPanel):
    def __init__(self, parent):
        scrolled.ScrolledPanel.__init__(self, parent)
        self.SetBackgroundColour(wx.WHITE)
        self.tel = wid.TitleTextLabel(self, "车辆:", "")
        self.testbegin = wid.TitleTextLabel(self, "测试开始:", "")
        self.testend = wid.TitleTextLabel(self, "测试截止:", "")
        
        self.record = RecordList(self)
        mainsizer = wid.Sizer(wx.VERTICAL, flag=wx.ALL|wx.EXPAND, border = 5)
        mainsizer.Attach(self.tel, self.testbegin, self.testend, wx.Size(-1,20))
        mainsizer.Add(self.record, proportion = 1)
        self.SetSizer(mainsizer)
        self.Fit()
        
    def setBasicInfo(self, tel, begin, end):
        self.tel.SetLabel(tel)
        self.testbegin.SetLabel(begin)
        self.testend.SetLabel(end)
        
    def showRecord(self, *args, **kw):
        self.GetParent().showRecord(*args, **kw)
        
    def showReport(self):
        tel, begin, end = record_info.getTestInfo()
        self.setBasicInfo(tel, begin, end)
        for record in record_info.getAllTestCaseInfo():
            self.record.insertRecord(*record)

class FunctionPanel(wx.ListCtrl):
    pass


class ReportPanel(aui.AuiNotebook):
    def __init__(self, parent):
        aui.AuiNotebook.__init__(self, parent, style=wx.BORDER_NONE)
        self.SetTabCtrlHeight(15)
        self.mainWindow = GeneralWindow(self)
        self.AddPage(self.mainWindow)
        
    def AddPage(self, control):
        cnt = self.GetPageCount()
        aui.AuiNotebook.AddPage(self, control, str(cnt))
        return cnt
        
    def showReport(self):
        global record_info
        if not record_info: return
        self.mainWindow.showReport()
                
    def showRecord(self, mark):
        panel = RecordPanel(self, mark)
        self.AddPage(panel)
        panel.showPanel()
        
            

def readRecord(path):
    global record_info
    if record_info:
        record_info.getConnection().close()
    conn = RecordConnection(path)
    record_info = RecordInfo(conn)
    if record_info.getTestInfo():
        return True
    return False          
            

class ReportForm(wx.Frame):
    def __init__(self, *args, **kw):
        wx.Frame.__init__(self, *args, **kw)
        self.mgr=aui.AuiManager()
        self.mgr.SetManagedWindow(self)
        
        self.operation = wid.OperationPanel(self, "")
        items = (
                 None,
                 (ico.getBmp("report"), wx.ITEM_NORMAL, u"打开报告", self.OnReportOpen),
                 )
        self.operation.layout(items)
        self.mgr.AddPane(self.operation, aui.AuiPaneInfo().Name(u"operation").Top().
                                        ToolbarPane().Floatable(False).MinSize((220,-1)))
        self.view = ReportPanel(self)
        self.mgr.AddPane(self.view, aui.AuiPaneInfo().Name(u"view").
                                        Caption(u"显示").Center().
                                        Floatable(False).MinSize((220,-1)).
                                        CloseButton(False).MaximizeButton(True))
        '''
        self.function = FunctionPanel(self)
        self.mgr.AddPane(self.function, aui.AuiPaneInfo().Name(u"function").
                                        Caption(u"功能").Left().
                                        Floatable(False).MinSize((150,-1)).
                                        CloseButton(False).MaximizeButton(False))
        '''
        self.mgr.Update()
        
        
    def OnReportOpen(self, evt):
        dlg = wid.OpenDialog(self, wildcard = "报表文件(*.report)|*.report")
        if dlg.ShowModal() == wx.ID_OK:
            path = dlg.GetPath()
            if readRecord(path):
                self.view.showReport()
            else:
                d = wid.WarningDialog(self, u"文件数据错误.%s"%e)
                d.ShowModal()
                d.Destroy()
        dlg.Destroy()
        
        
 
        
        

if __name__ == '__main__':
    app = wx.App(0)
    f = ReportForm(None)
    f.Show()
    f.SetSize((800,500))
    app.MainLoop()